﻿using FMusicReload.Utils;
using HTBInject.Utils;
using Newtonsoft.Json.Linq;
using System;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows;
using System.Windows.Threading;

namespace FMusicReload
{
    public partial class App : Application
    {
        #region 资源回收
        [DllImport("kernel32.dll")]
        public static extern bool SetProcessWorkingSetSize(IntPtr proc, int min, int max);


        public static void CollectRam()
        {
            GC.Collect();
            GC.WaitForFullGCComplete();
            if (Environment.OSVersion.Platform == PlatformID.Win32NT)
                SetProcessWorkingSetSize(System.Diagnostics.Process.GetCurrentProcess().Handle, -1, -1);
        }
        #endregion

        #region 资源加载
        private static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
        {
            string resourceName = "FMusicReload.Library." + new AssemblyName(args.Name).Name + ".dll";

            using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName))
            {
                if (stream != null)
                {
                    byte[] assemblyData = new byte[stream.Length];
                    stream.Read(assemblyData, 0, assemblyData.Length);
                    return Assembly.Load(assemblyData);
                }

                return null;
            }
        }
        #endregion

        public App()
        {
            AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;

            var timer = new DispatcherTimer { Interval = TimeSpan.FromMinutes(10) };
            timer.Tick += (s, e) => CollectRam();
            timer.Start();

            AppNotifyManger.GetCtx().AddItem(new CtxItem("退出FMusic", "\ue8bb", GetType().GetMethod("ExitApp"), this));

            AppNotifyManger.Init();

            SettingManger.Init();
            LogSever.LogsFileLocation = AssetsManger.GetFolderPath() + "\\logs.log";
            LogSever.Init();
            AssetsManger sm = new AssetsManger();

            
            if (!File.Exists(AssetsManger.GetFolderPath() + "\\tbs.icon.is.install.sure"))
            {
                File.WriteAllBytes("icon_install_package", Convert.FromBase64String((string)AssetsManger.GetAssets(AssetsManger.Type.type_string, "icon")));
                try { if (!FontOperate.InstallFont("icon_install_package")) return; }
                catch(Exception e)
                {
                    MessageBox.Show("Application Interlize Error at " + e.Source + " is " + e.Message, "Runtime Error", MessageBoxButton.OK, MessageBoxImage.Error);
                    Thread.Sleep(1000);
                    return;
                }
                File.Delete("icon_install_package");
                File.Create(AssetsManger.GetFolderPath() + "\\tbs.icon.is.install.sure");
                GC.Collect();
            }
        }

        public void ExitApp()
        {
            MainWindow.Close();
            GC.Collect();
            AppNotifyManger.Dispose();
            Environment.Exit(0);
        }
    }
}
